#include "Triangle.h"
#include <GL/glut.h>



Triangle::Triangle(Vector3<float> p1, Vector3<float> p2, Vector3<float> p3)
{
	Points[0] = p1;
	Points[1] = p2;
	Points[2] = p3;

	Vector3<float> v1 = p1 - p2;
	Vector3<float> v3 = p3 - p2;
	Normal = v3.Cross(v1).Normal();
}

Triangle::Triangle(Vector3<float> pts[3])
{
	Points[0] = pts[0];
	Points[1] = pts[1];
	Points[2] = pts[2];

	Vector3<float> v1 = pts[0] - pts[1];
	Vector3<float> v3 = pts[2] - pts[1];
	Normal = v3.Cross(v1).Normal();
}

Triangle::~Triangle(void)
{
}

void Triangle::Draw()
{
	glVertex3f(Points[0].X(), Points[0].Y(), Points[0].Z());
	glVertex3f(Points[1].X(), Points[1].Y(), Points[1].Z());
	glVertex3f(Points[2].X(), Points[2].Y(), Points[2].Z());
}

void Triangle::DrawNormal()
{
	Vector3<float> avg = Points[0] + Points[1] + Points[2];
	avg *= 0.33333333;
	Vector3<float> nPlus = avg + (Normal);

	glBegin(GL_LINES);
	glColor3f(1,1,1);

	glVertex3f(avg.X(), avg.Y(), avg.Z());
	glVertex3f(nPlus.X(), nPlus.Y(), nPlus.Z());

	glEnd();


}

Triangle Triangle::Transformed(MyMatrix mix)
{
	Vector3<float> pts[3];

	MyMatrix movedPoint(1,4);
	MyMatrix point(1,4);

	for(int i = 0; i < 3; i++)
	{
		point.at(0,0) = Points[i].X();
		point.at(0,1) = Points[i].Y();
		point.at(0,2) = Points[i].Z();
		point.at(0,3) = 1;

		movedPoint = mix * point;
	
		// new transformed point
		pts[i] = Vector3<float>(movedPoint.at(0,0), movedPoint.at(0,1), movedPoint.at(0,2));
	}

	return Triangle(pts);
}

Vector3<float> Triangle::TranfomredNormal(MyMatrix mix)
{
	Vector3<float> pts[3];

	MyMatrix movedPoint(1,4);
	MyMatrix point(1,4);

	for(int i = 0; i < 3; i++)
	{
		point.at(0,0) = Points[i].X();
		point.at(0,1) = Points[i].Y();
		point.at(0,2) = Points[i].Z();
		point.at(0,3) = 0;

		movedPoint = mix * point;
		// new transformed point
		pts[i] = Vector3<float>(movedPoint.at(0,0), movedPoint.at(0,1), movedPoint.at(0,2));
	}
	// get the normal
	Vector3<float> v1 = pts[0] - pts[1];
	Vector3<float> v3 = pts[2] - pts[1];
	return v3.Cross(v1).Normal();
}